<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;

/**
 * 门店管理
 *
 * @icon fa fa-circle-o
 */
class Store extends Backend
{

    /**
     * Store模型对象
     * @var \app\admin\model\Store
     */
    protected $model = null;
    //当前登录管理员所有子组别
    protected $childrenGroupIds = [];
    //当前组别列表数据
    protected $grouplist = [];
    protected $groupdata = [];
    //无需要权限判断的方法
    protected $noNeedRight = ['roletree'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Store;
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);
        $where['pid'] = 0;
        $groupList = collection(AuthGroup::where($where)->select())->toArray();
        Tree::instance()->init($groupList);

        $groupName = [];
        foreach ($groupList as $k => $v) {
            $groupName[$v['id']] = $v['name'];
        }

        $this->grouplist = $groupList;
        $this->groupdata = $groupName;
        $this->assignconfig("admin", ['id' => $this->auth->id, 'group_ids' => $this->auth->getGroupIds()]);

        $this->view->assign('groupdata', $this->groupdata);
    }


    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        if($this->withModel){
            $this->model->with($this->withModel);
        }
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit)->each(function ($item,$index){
                $code = $item['province'].",".$item['city'].",".$item['area'];
                $sql = "select name from ws_area where code IN (".$code.") order by field(code,".$code.")";
                $result = Db::query($sql);
                $item['province'] = $result[0]['name'];
                $item['city'] = $result[1]['name'];
                $item['area'] = $result[2]['name'];
            });
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a", [], 'strip_tags');

            $rules = explode(',', $params['rules']);
            if (!in_array($params['pid'], $this->childrenGroupIds)) {
                $this->error(__('The parent group exceeds permission limit'));
            }
            $parentmodel = model("AuthGroup")->get($params['pid']);
            if (!$parentmodel) {
                $this->error(__('The parent group can not found'));
            }
            // 父级别的规则节点
            $parentrules = explode(',', $parentmodel->rules);
            // 当前组别的规则节点
            $currentrules = $this->auth->getRuleIds();
            // 如果父组不是超级管理员则需要过滤规则节点,不能超过父组别的权限
            $rules = in_array('*', $parentrules) ? $rules : array_intersect($parentrules, $rules);
            // 如果当前组别不是超级管理员则需要过滤规则节点,不能超当前组别的权限
            $rules = in_array('*', $currentrules) ? $rules : array_intersect($currentrules, $rules);

            $store = \app\admin\model\Store::get(['name'=>$params['name']]);
            if($store){
                $this->error("名称已存在");
            }
            $authdata['status'] = $params['status'];
            $authdata['pid'] = $params['pid'];
            $authdata['name'] = $params['name'];
            $authdata['type'] = 2;
            $authdata['rules'] = implode(',', $rules);
            $authdata['createtime'] = time();
            $authdata['updatetime'] = time();

            $city = explode("/",$params['code']);
            if(!is_numeric($city[0]) || !is_numeric($city[1]) || !is_numeric($city[2])){
                $this->error("请选择正确的地区");
            }

            $info['logo'] = $params['logo'];
            $info['name'] = $params['name'];
            $info['phone'] = $params['phone'];
            $info['province'] = $city[0];
            $info['city'] = $city[1];
            $info['area'] = $city[2];
            $info['address'] = $params['address'];
            $info['intro'] = $params['intro'];
            $info['status'] = $params['status'];

            Db::startTrans();
            try {
                $authGroup = new AuthGroup();
                $authGroupId = $authGroup->insertGetId($authdata);
                if(!$authGroupId){
                    Db::rollback();
                    $this->error("保存失败");
                }
                $info['auth_group_id'] = $authGroupId;
                $storeRe = \app\admin\model\Store::create($info);
                if ($storeRe){
                    Db::commit();
                    $this->success();
                }else{
                    Db::rollback();
                    $this->error("保存失败");
                }
            }catch (DbException $e){
                Db::rollback();
                $this->error("保存失败");
            }
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = \app\admin\model\Store::with('auth_group')
            ->where(['id' => $ids])
            ->find();

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        $code = $row['province'].",".$row['city'].",".$row['area'];
        $sql = "select name from ws_area where code IN (".$code.") order by field(code,".$code.")";
        $area = Db::query($sql);
        $row['code'] = str_replace(",","/",$code);
        $row['city'] = $area[0]['name']."/".$area[1]['name']."/".$area[2]['name'];

        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a", [], 'strip_tags');

            $rules = explode(',', $params['rules']);

            $parentmodel = model("AuthGroup")->get($params['pid']);
            if (!$parentmodel) {
                $this->error(__('The parent group can not found'));
            }
            // 父级别的规则节点
            $parentrules = explode(',', $parentmodel->rules);
            // 当前组别的规则节点
            $currentrules = $this->auth->getRuleIds();
            // 如果父组不是超级管理员则需要过滤规则节点,不能超过父组别的权限
            $rules = in_array('*', $parentrules) ? $rules : array_intersect($parentrules, $rules);
            // 如果当前组别不是超级管理员则需要过滤规则节点,不能超当前组别的权限
            $rules = in_array('*', $currentrules) ? $rules : array_intersect($currentrules, $rules);
            $params['rules'] = implode(',', $rules);
            if ($params) {
                $where['name'] = $params['name'];
                $store = \app\admin\model\Store::where($where)->find();
                if($store && ($row['id']!=$store['id'])){
                    $this->error("名称已存在");
                }

                $authdata['status'] = $params['status'];
                $authdata['pid'] = $params['pid'];
                $authdata['name'] = $params['name'];
                $authdata['rules'] = $params['rules'] ;
                $authdata['updatetime'] = time();

                $city = explode("/",$params['code']);
                if(!is_numeric($city[0]) || !is_numeric($city[1]) || !is_numeric($city[2])){
                    $this->error("请选择正确的地区");
                }
                $info['logo'] = $params['logo'];
                $info['name'] = $params['name'];
                $info['phone'] = $params['phone'];
                $info['province'] = $city[0];
                $info['city'] = $city[1];
                $info['area'] = $city[2];
                $info['address'] = $params['address'];
                $info['intro'] = $params['intro'];
                $info['status'] = $params['status'];
                $info['updatetime'] = time();

                Db::startTrans();
                try {
                    $re1 = AuthGroup::where(['id'=>$row['auth_group_id']])->update($authdata);
                    $children_auth_groups = model("AuthGroup")->all(['id' => ['in', implode(',', (Tree::instance()->getChildrenIds($row['auth_group_id'])))]]);
                    $childparams = [];
                    $re2 = true;
                    if($children_auth_groups){
                        foreach ($children_auth_groups as $key => $children_auth_group) {
                            $childparams[$key]['id'] = $children_auth_group->id;
                            $childparams[$key]['rules'] = implode(',', array_intersect(explode(',', $children_auth_group->rules), $rules));
                        }
                        //更新子分组的rules 因为当前分组rules变化了，所以子分组的也要跟着变化，求原来分组和当前分组rules的交集
                        $re2 = model("AuthGroup")->saveAll($childparams);
                    }
                    $re3 = \app\admin\model\Store::where(['id'=>$ids])->update($info);
                    if($re1 && $re2 && $re3){
                        Db::commit();
                        $this->success();
                    }else{
                        Db::rollback();
                        $this->error("保存失败");
                    }
                } catch (DbException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }

        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                //设置门店下所有账号状态为hidden
                Admin::where(['store_id'=>['in',$item->id]])->update(['status'=>'hidden']);
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

    /**
     * 读取角色权限树
     * @internal
     */
    public function roletree()
    {
        $this->loadlang('auth/group');

        $model = model('AuthGroup');
        $id = $this->request->post("id");
        $pid = $this->request->post("pid");
        $parentGroupModel = $model->get($pid);
        $currentGroupModel = null;
        if ($id) {
            $currentGroupModel = $model->get($id);
        }
        if (($pid || $parentGroupModel) && (!$id || $currentGroupModel)) {
            $id = $id ? $id : null;
            $ruleList = collection(model('AuthRule')->where("FIND_IN_SET(2,belongs)")->order('weigh', 'desc')->order('id', 'asc')->select())->toArray();
            //读取父类角色所有节点列表
            $parentRuleList = [];
            if (in_array('*', explode(',', $parentGroupModel->rules))) {
                $parentRuleList = $ruleList;
            } else {
                $parentRuleIds = explode(',', $parentGroupModel->rules);
                foreach ($ruleList as $k => $v) {
                    if (in_array($v['id'], $parentRuleIds)) {
                        $parentRuleList[] = $v;
                    }
                }
            }

            $ruleTree = new Tree();
            $groupTree = new Tree();
            //当前所有正常规则列表
            $ruleTree->init($parentRuleList);
            //角色组列表
            $groupTree->init(collection(model('AuthGroup')->where('id', 'in', $this->childrenGroupIds)->select())->toArray());

            //读取当前角色下规则ID集合
            $adminRuleIds = $this->auth->getRuleIds();
            //是否是超级管理员
            $superadmin = $this->auth->isSuperAdmin();
            //当前拥有的规则ID集合
            $currentRuleIds = $id ? explode(',', $currentGroupModel->rules) : [];

            if (!$id || !in_array($pid, $this->childrenGroupIds) || !in_array($pid, $groupTree->getChildrenIds($id, true))) {
                $parentRuleList = $ruleTree->getTreeList($ruleTree->getTreeArray(0), 'name');
                $hasChildrens = [];
                foreach ($parentRuleList as $k => $v) {
                    if ($v['haschild']) {
                        $hasChildrens[] = $v['id'];
                    }
                }
                $parentRuleIds = array_map(function ($item) {
                    return $item['id'];
                }, $parentRuleList);
                $nodeList = [];
                foreach ($parentRuleList as $k => $v) {
                    if (!$superadmin && !in_array($v['id'], $adminRuleIds)) {
                        continue;
                    }
                    if ($v['pid'] && !in_array($v['pid'], $parentRuleIds)) {
                        continue;
                    }
                    $state = array('selected' => in_array($v['id'], $currentRuleIds) && !in_array($v['id'], $hasChildrens));
                    $nodeList[] = array('id' => $v['id'], 'parent' => $v['pid'] ? $v['pid'] : '#', 'text' => __($v['title']), 'type' => 'menu', 'state' => $state);
                }
                $this->success('', null, $nodeList);
            } else {
                $this->error(__('Can not change the parent to child'));
            }
        } else {
            $this->error(__('Group not found'));
        }
    }

}
